// #ifdef APP-PLUS
import permision from "@/js_sdk/wa-permission/permission.js"
var locationModule = uni.requireNativePlugin('LocationModule');
// #endif
class Gps {
	constructor(uploadTime=180000) {
		this.lock = false //锁防止重复请求
		this.Interval = null // 定时器
		this.listener = null // 微信小程序位置获取函数
		this.uploadTime = uploadTime
		this.lastUploadTime = 0
		
		this.logFn = null
	}
	init() {
		this.lock = false
		this.Interval = null
		this.lastUploadTime = 0
	}
	async getLocation(param = {
		type: 'wgs84'
	}, task = {}, uploadFn, next, poll = false) {
		return new Promise(async (callback) => {
			if (this.lock) {
				console.log('已锁，已有另一个请求正在执行。无需重复请求');
				callback(false);
				return false
			}
			this.lock = true //加锁防止重复的请求
			// #ifdef MP-WEIXIN
			const state = await this.checkAuth('userLocation')
			if (!state) {
				callback(false)
				return false
			}
			// #endif
			uni.getLocation({
				...param,
				success: res => {
					this.lock = false //成功后解锁
					callback(res)
				},
				fail: async (err) => {
					// uni.showToast({
					// 	title: '定位获取失败',
					// 	icon: 'none'
					// });
					console.error(err)
					callback(false)
					
					// #ifdef APP-PLUS
					await this.checkGpsIsOpen(callback)
					return false
					// #endif
					
					// #ifdef MP-WEIXIN
					if (err.errMsg == 'getLocation:fail auth deny') {
						uni.showToast({
							title: '拒绝授权',
							icon: 'none'
						});
						return false
					}
					if (
						err.errMsg == 'getLocation:fail:ERROR_NOCELL&WIFI_LOCATIONSWITCHOFF' ||
						err.errMsg == 'getLocation:fail system permission denied' ||
						err.errMsg === 'getLocation:fail:system permission denied'
					) {
						uni.showModal({
							title: '提示',
							content: '未开启定位权限，请前往手机系统设置中开启，如已开启请尝试重新进入小程序',
							showCancel: false,
							confirmText:"知道了",
							success: () => {
								this.lock = false
							}
						});
						return false
					}
					// #endif
					
					this.logFn && this.logFn(`获取位置信息失败，${err.errMsg}`)
					if (next) {
						// 当开启位置的错误不为定位设置未开启的情况,仍然执行下一步
						// this.logFn && this.logFn(`进入下一步，改变状态`)
						next(task)
					}
					if (poll) {
						this.logFn && this.logFn(`即将进入循环函数`)
						const loc = await this.pollLocation()
						if (loc) {
							this.lastUploadTime = 0
							uni.setStorageSync('gpsUploadTime', 0)
							uploadFn && uploadFn(task, loc)
							this.lock = false
							// this.startLoctionBackgroundUpdate(task, uploadFn, false)
						}
					}
				}
			});
		})
	}
	async startLoctionBackgroundUpdate(task = {}, uploadFn, next, poll=true) {
		return new Promise(async (callback) => { 
			// #ifdef MP-WEIXIN
			if (this.lock) {
				console.log('已锁，已有另一个请求正在执行。无需重复请求');
				callback(false);
				return false
			}
			this.lock = true //加锁防止重复的请求 成功后不用解锁，防止放在onShow中时，重复开启
			const state = await this.checkAuth('userLocationBackground')
			if (!state) {
				callback(false)
				return false
			}
			this.lastUploadTime = 0
			// if (this.listener) {
			// 	// this.listener = null;
			// 	uni.offLocationChange(this.listener)
			// }
			uni.stopLocationUpdate({ // 不加stop系统的权限询问弹窗只会第一次显示，并且手动切换系统设置后onLocationChange需要手动刷新才会执行
				complete: () => {
					uni.startLocationUpdateBackground({
						success: async (res) => {
							console.log(res, "startLocationUpdateBackground")
							this.logFn && this.logFn(`开启位置监听成功`)
							console.log(task)
							if (next) {
								next(task)
							}
							if (this.listener) {
								uni.offLocationChange()
							}
							this.task = task
							this.listener = (res) => {
								console.log(res)
								this.lock = false
								if (this.lastUploadTime == 0) {
									this.logFn && this.logFn(`位置信息，${JSON.stringify(res)}`)
									uni.setStorageSync('gpsUploadTime', 0)
								}
								callback(res)
								let nowDate = new Date().getTime()
								console.log(nowDate - this.lastUploadTime)
								if (nowDate - this.lastUploadTime > this.uploadTime) {
									this.lastUploadTime = nowDate
									uploadFn && uploadFn(this.task, res)
								}
							}
							uni.onLocationChange(this.listener)
							uni.onLocationChangeError((errCode) => {
								console.log(errCode, "onLocationChangeError")
								this.logFn && this.logFn(`位置获取失败，${errCode}`)
								this.lock = false //解锁，轨迹上传中修改了设置
								callback(false);
							})
						},
						fail: async (err) => {
							console.log(err, "startLocationUpdateBackgroundError")
							// uni.showToast({
							// 	title: '位置获取失败',
							// 	icon: 'none'
							// })
							this.logFn && this.logFn(`开启位置监听失败，${err.errMsg}`)
							callback(false)
							
							if (err.errMsg == 'startLocationUpdateBackground:fail auth deny') {
								uni.showModal({
									title: '司机小程序"需要获取您的当前位置',
									content: `请点击设置->打开位置信息->使用小程序期间和离开小程序后`,
									confirmText: '去设置',
									complete: e => {
										if (e.confirm) {
											uni.openSetting({
												success: (dataAu) => {
													if (dataAu.authSetting["scope.userLocationBackground"] == true) {
														//再次授权，调用getLocation的API
														console.log(`%cuni.openSetting成功：`, 'color:green;background:yellow')
													} else {
														console.log(`%cuni.openSetting失败：`, 'color:green;background:yellow');
													}
												}
											})
										}
										this.lock = false //解锁让回到界面重新获取
									}
								})
								return false
							} 
							if (
								err.errMsg == 'startLocationUpdateBackground:fail:ERROR_NOCELL&WIFI_LOCATIONSWITCHOFF' ||
								err.errMsg == 'startLocationUpdateBackground:fail system permission denied' ||
								err.errMsg === 'startLocationUpdateBackground:fail:system permission denied'
							) {
								// uni.showModal({
								// 	title: '提示',
								// 	content: '未开启定位权限，请前往手机系统设置中开启，如已开启请尝试重新进入小程序',
								// 	showCancel: false, // 不显示取消按钮
								// 	complete: e => {
								// 		this.lock = false
								// 	}
								// })
								uni.showToast({
									title: "未开启定位权限，请前往手机系统设置中开启",
									icon: 'none'
								})
								this.lock = false
								return false
							}
							if (next) {
								// 当开启位置的错误不为定位设置未开启的情况,仍然执行下一步
								// this.logFn && this.logFn(`进入下一步，改变状态`)
								next(task)
							}
							if (poll) {
								this.logFn && this.logFn(`即将进入循环函数`)
								const loc = await this.pollLocation()
								if (loc) {
									this.lastUploadTime = 0
									uni.setStorageSync('gpsUploadTime', 0)
									uploadFn && uploadFn(task, loc)
									this.lock = false
									// this.startLoctionBackgroundUpdate(task, uploadFn, false)
								}
							}
						}
					})
				}
			})
			// #endif
			// #ifdef APP-PLUS
			if (uni.getSystemInfoSync().platform == "ios") {
				console.log('ios')
				this.Interval && clearInterval(this.Interval)
				if (next) {
					next(task)
				}
				let that = this
				that.logFn && that.logFn(`ios开始获取位置`)
				const target = async (task, uploadFn, next, poll) => {
					let result = await that.getLocation({ type: 'wgs84' }, task, uploadFn, next, poll)
					if (that.lastUploadTime == 0) {
						that.logFn && that.logFn(`位置信息，${JSON.stringify(result)}`)
						this.lastUploadTime = new Date().getTime()
						uni.setStorageSync('gpsUploadTime', 0)
					}
					if (result) {
						uploadFn && uploadFn(task, result)
						callback(result)
					} else {
						callback(false)
					}
				}
				target(task, uploadFn, next, poll)
				this.Interval = setInterval(() => target(task, uploadFn, next, poll), this.uploadTime)
			} else {
					this.Interval && clearInterval(this.Interval)
					if (next) {
						next(task)
					}
					let that = this
					that.logFn && that.logFn(`android开始获取位置`)
					const target = async () => {
						let result = await that.getLocation({ type: 'wgs84' }, task, uploadFn, next, poll)
						if (that.lastUploadTime == 0) {
							that.logFn && that.logFn(`位置信息，${JSON.stringify(result)}`)
							this.lastUploadTime = new Date().getTime()
							uni.setStorageSync('gpsUploadTime', 0)
						}
						if (result) {
							uploadFn && uploadFn(task, result)
							callback(result)
						} else {
							callback(false)
						}
					}
					target()
					this.Interval = setInterval(() => target(), this.uploadTime)
					// return
				let result = await this.getLocation({ type: 'wgs84' }, task, uploadFn, next, poll)
				if (result) {
					// let StartLongitude = ''
					// let StartLatitude = ''
					// let EndLongitude = ''
					// let EndLatitude = ''
					// const [startResult, endResult] = await Promise.all([this.addressToLatAndLon(task.shippingCity), this.addressToLatAndLon(task.receiptCity)])
					// if (startResult.data && startResult.data.geocodes.length > 0) {
					// 	StartLongitude = startResult.data.geocodes[0].location.split(',')[0]
					// 	StartLatitude = startResult.data.geocodes[0].location.split(',')[1]
					// }
					// if (endResult.data && endResult.data.geocodes.length > 0) {
					// 	 EndLongitude = endResult.data.geocodes[0].location.split(',')[0]
					// 	 EndLatitude = endResult.data.geocodes[0].location.split(',')[1]
					// }
					// console.log(StartLongitude,StartLatitude,EndLongitude,EndLatitude)
					console.log(task)
					locationModule.start({
							appSecurity: task.appSecurity,
							enterpriseSenderCode: task.enterpriseSenderCode,
							ShippingNoteNumber: task.loadingOrderId,
							StartCountrySubdivisionCode: task.shippingRegionCode,
							EndCountrySubdivisionCode: task.receiptRegionCode,
							StartLongitude: task.shippingLng,
							StartLatitude: task.shippingLat,
							EndLongitude: task.receiptLng,
							EndLatitude: task.receiptLat,
							StartLocationText: task.shippingCity,
							EndLocationText: task.receiptCity,
							VehicleNumber: task.vehicleNo,
							DriverName: task.driverName
						},
						async ret => {
							console.log(ret)
							let rets = ret.code;
							this.logFn && this.logFn(`androidSDK调用结果${JSON.stringify(ret)}`)
							// if (rets == '发送定位send成功') {
								// this.Interval && clearInterval(this.Interval)
								// if (next) {
								// 	next(task)
								// }
								// let that = this
								// that.logFn && that.logFn(`android开始获取位置`)
								// const target = async () => {
								// 	let result = await that.getLocation({ type: 'wgs84' }, task, uploadFn, next, poll)
								// 	if (that.lastUploadTime == 0) {
								// 		that.logFn && that.logFn(`位置信息，${JSON.stringify(result)}`)
								// 		this.lastUploadTime = new Date().getTime()
								// 		uni.setStorageSync('gpsUploadTime', 0)
								// 	}
								// 	if (result) {
								// 		uploadFn && uploadFn(task, result)
								// 		callback(result)
								// 	} else {
								// 		callback(false)
								// 	}
								// }
								// target()
								// this.Interval = setInterval(() => target(), this.uploadTime)
							// }
						}
					)
				}
			}
			// #endif
		})
	}
	async stopLocationUpdate(task, uploadFn, next, poll=true) {
		const that = this
		return new Promise(async (callback) => {
			// #ifdef MP-WEIXIN
			uni.stopLocationUpdate()
			this.lock = false
			this.lastUploadTime = 0
			uni.setStorageSync('gpsUploadTime', 0)
			this.logFn && this.logFn(`weixin开始获取位置`)
			let result = await that.getLocation({ type: 'wgs84' }, task, uploadFn, next, poll)
			this.logFn && this.logFn(`位置信息，${JSON.stringify(result)}`)
			if (result) {
				uploadFn && uploadFn(task, result)
				callback(result)
			} else {
				callback(false)
			}
			// #endif
			// #ifdef APP-PLUS
			if (uni.getSystemInfoSync().platform == "ios") {
				this.Interval && clearInterval(this.Interval)
				this.lock = false
				this.lastUploadTime = 0
				uni.setStorageSync('gpsUploadTime', 0)
				this.logFn && this.logFn(`ios开始获取位置`)
				let result = await that.getLocation({ type: 'wgs84' }, task, uploadFn, next, poll)
				this.logFn && this.logFn(`位置信息，${JSON.stringify(result)}`)
				if (result) {
					uploadFn && uploadFn(task, result)
					callback(result)
				} else {
					callback(false)
				}
			} else {
				this.Interval && clearInterval(this.Interval)
				this.lock = false
				this.lastUploadTime = 0
				uni.setStorageSync('gpsUploadTime', 0)
				this.logFn && this.logFn(`android开始获取位置`)
				let result = await that.getLocation({ type: 'wgs84' }, task, uploadFn, next, poll)
				this.logFn && this.logFn(`位置信息，${JSON.stringify(result)}`)
				if (result) {
					uploadFn && uploadFn(task, result)
					callback(result)
				} else {
					callback(false)
					return false
				}
				// let StartLongitude = ''
				// let StartLatitude = ''
				// let EndLongitude = ''
				// let EndLatitude = ''
				// const [startResult, endResult] = await Promise.all([this.addressToLatAndLon(task.shippingCity), this.addressToLatAndLon(task.receiptCity)])
				// if (startResult.data && startResult.data.geocodes.length > 0) {
				// 	StartLongitude = startResult.data.geocodes[0].location.split(',')[0]
				// 	StartLatitude = startResult.data.geocodes[0].location.split(',')[1]
				// }
				// if (endResult.data && endResult.data.geocodes.length > 0) {
				// 	 EndLongitude = endResult.data.geocodes[0].location.split(',')[0]
				// 	 EndLatitude = endResult.data.geocodes[0].location.split(',')[1]
				// }
				locationModule.stop({
					appSecurity: task.appSecurity,
					enterpriseSenderCode: task.enterpriseSenderCode,
					ShippingNoteNumber: task.loadingOrderId,
					StartCountrySubdivisionCode: task.shippingRegionCode,
					EndCountrySubdivisionCode: task.receiptRegionCode,
					StartLongitude: task.shippingLng,
					StartLatitude: task.shippingLat,
					EndLongitude: task.receiptLng,
					EndLatitude: task.receiptLat,
					StartLocationText: task.shippingCity,
					EndLocationText: task.receiptCity,
					VehicleNumber: task.vehicleNo,
					DriverName: task.driverName
				},
				ret => {
					
				})
				
			}
			// #endif
		})
	}
	clearLocationUpdate() {
		if (this.lastUploadTime) {
			// #ifdef MP-WEIXIN
			uni.stopLocationUpdate()
			this.lastUploadTime = 0
			// #endif
			// #ifdef APP-PLUS
			this.Interval && clearInterval(this.Interval)
			this.lastUploadTime = 0
			// #endif
		}
	}
	// #ifdef APP-PLUS
	async checkGpsIsOpen(callback) {
		this.lock = true //加锁防止重复的请求
		console.log('检查定位设置开启问题', permision.checkSystemEnableLocation());
		if (!permision.checkSystemEnableLocation()) {
			plus.nativeUI.confirm("手机定位权限没有开启，是否去开启？", (e) => {
				this.lock = false
				if (e.index == 0) {
					if (uni.getSystemInfoSync().platform == "ios") {
						plus.runtime.openURL("app-settings://");
					} else {
						var main = plus.android.runtimeMainActivity(); //获取activity
						var Intent = plus.android.importClass('android.content.Intent');
						var Settings = plus.android.importClass('android.provider.Settings');
						var intent = new Intent(Settings
						.ACTION_LOCATION_SOURCE_SETTINGS); //可设置表中所有Action字段  
						main.startActivity(intent);
					}
				} else {
					uni.showToast({
						title: '设备无定位权限',
						icon: 'none'
					});
					callback(false)
				}
			}, {
				"buttons": ["去设置", "不开启"],
				"verticalAlign": "center"
			});
			return false
		}
		let checkAppGpsRes = await this.checkAppGps()
		console.log(checkAppGpsRes, 'checkAppGpsRes');
		if (!checkAppGpsRes) {
			plus.nativeUI.confirm("应用定位权限没有开启，是否去开启？", (e) => {
				this.lock = false
				if (e.index == 0) {
					permision.gotoAppPermissionSetting()
					callback(false)
				} else {
					uni.showToast({
						title: '应用无定位权限',
						icon: 'none'
					});
					return false
				}
			}, {
				"buttons": ["去设置", "不开启"],
				"verticalAlign": "center"
			});
			return false
		} else {
			this.lock = false
			return true
		}
	}
	async checkAppGps() {
		if (uni.getSystemInfoSync().platform == "ios" && !permision.judgeIosPermission("location")) {
			return false
		}
		if (uni.getSystemInfoSync().platform != "ios" && await permision.requestAndroidPermission(
				"android.permission.ACCESS_FINE_LOCATION") != 1) {
			return false
		}
		return true
	}
	// #endif
	// 循环获取定位函数
	pollLocation(delay=2000) {
		return new Promise((resolve, reject) => {
			const poll = (num=1) => {
				if (num > 5) return
				uni.getLocation({
					type: 'wgs84',
					success: res => {
						resolve(res)
						this.logFn && this.logFn(`循环第${num}次成功，${JSON.stringify(res)}`)
					},
					fail: err => {
						this.logFn && this.logFn(`循环第${num}次失败，${JSON.stringify(err)}`)
						setTimeout(poll, delay, ++num)
					}
				})
			};
			poll();
		});
	}
	// #ifdef MP-WEIXIN
	checkSystemLocation() {
		return new Promise((resolve, reject) => {
			// 1、判断手机定位服务【GPS】 是否授权
			this.lock = true
			uni.getSystemInfo({
				success: (res) => {
					console.log(res)
					if (!res.locationEnabled || !res.locationAuthorized) {
					// if (!res.locationEnabled) {
						//手机定位服务（GPS）未授权
						uni.showModal({
							title: '提示',
							content: '请开启手机gps定位,设置-隐私-位置',
							showCancel: true, // 不显示取消按钮
							complete: e => {
								this.lock = false
							}
						})
						resolve(false)
						return false;
					} else {
						resolve(true)
					}
				},
				fail:(err) => {
					this.lock = false
					resolve(false)
					return false
				}
			})
						
		})
	}
	// #endif
	
	// #ifdef MP-WEIXIN
	// 检测当前请求权限是否可用。
	checkAuth(scopeValue) {
		const that = this;
		return new Promise((resolve, reject) => {
			console.log(that.lock, 'ttttt')
			uni.getSetting({
				success: res => {
					console.log(scopeValue)
					console.log(res)
					console.log(res.authSetting[`scope.${scopeValue}`])
					if (!res.authSetting[`scope.${scopeValue}`]) {
						uni.authorize({ //如果没请求过，会弹窗询问。同意过，直接success。此前拒绝，直接fai
							scope: `scope.${scopeValue}`,
							success: res => { //用户同意
								resolve(1)
							},
							fail: err => { //用户拒绝
								resolve(0)
								wx.showModal({
									title: '司机小程序"需要获取您的当前位置"',
									content: '请点击设置->打开位置信息->使用小程序期间和离开小程序后',
									confirmText: '去设置',
									cancelText: '取消',
									success: (ress) => {
										if (ress.cancel) {
											wx.showToast({
												title: '拒绝授权',
												icon: 'none',
											});
										} else if (ress.confirm) {
											wx.openSetting({
												success(dataAu) {
													console.log(dataAu)
												},
											});
										}
										that.lock = false
									},
								});
								
							}
						})
					} else {
						resolve(1)
					}
				},
				fail: err => {
					console.log(`%cuni.getSetting失败：`, 'color:green;background:yellow');
					console.log(err);
				}
			})
		})
	}
	// #endif
	
	//获取起运市区的经纬度
	addressToLatAndLon(address) {
		return new Promise((resolve, reject) => {
			uni.request({
				url: `https://restapi.amap.com/v3/geocode/geo?key=95415c2325d40e02db55eca83da41848&address=${address}`,
				method: 'GET',
				success: res => {
					resolve(res)
				},
				fail: err => {
					uni.showToast({
						title: '网络异常！',
						icon: 'none'
					});
					reject(err)
				}
			})
		})
	}
}
export default Gps
